# -*- coding: utf-8 -*-
# @Time    : 2024/8/27 10:15
# @Author  : Jonny
# @File    : LuckGitlabLogMain.py
# @Describe: GitlabLog入口
from flask import Blueprint, request, current_app
import time
from datetime import datetime, timedelta
import json
from luck.core.LuckConstant import LuckConstant
from luck.gitlab.LuckGitlabLogService import LuckGitlabLogService

luck_gitlab_log_bp = Blueprint('luck_gitlab_log', __name__)


# 检查服务器资源服务状态
@luck_gitlab_log_bp.route('/gitlab/log')
def gitlab_log_index():
    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 查看Gitlab部署服务')

    return {
        "code": LuckConstant.CODE_SUCCESS,
        "data": [
            "/"
            , "/gitlab/log/webhook"
            , "/gitlab/log/readLastOne"
            , "/gitlab/log/readAll"
            , "/gitlab/log/readCommitData?day_num=1"
        ],
        "msg": "Gitlab部署服务"
    }

# webhook事件
@luck_gitlab_log_bp.route('/gitlab/log/webhook', methods=['POST'])
def gitlab_log_webhook():
    print(f'于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 触发Webhook')

    data = json.loads(request.data)
    print('webhook参数：', data)
    project_code = data['project_code']
    day_num = 1
    __gitlab_log_read_commit_data(day_num, project_code)
    return {
        "code": LuckConstant.CODE_SUCCESS,
        "msg": "同步gitlab数据成功"
    }


# 读取指定项目最近提交日志
@luck_gitlab_log_bp.route("/gitlab/log/readLastOne", methods=['POST'])
def gitlab_log_read_last_one():
    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))}开始读取指定项目最近提交日志')
    config = current_app.config['CONFIG_DATA']
    data = json.loads(request.data)

    service = LuckGitlabLogService(config)
    print(f"读取指定项目最近提交日志参数：{data}")
    parameters = {
        "project_code": data["project_code"]
    }
    result = service.read(parameters)["data"]

    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 结束读取指定项目最近提交日志')
    if len(result) > 0:
        return {
                "code": LuckConstant.CODE_SUCCESS,
                "msg": "操作成功",
                "data": result[0]
            }
    return {
                "code": LuckConstant.CODE_SUCCESS,
                "msg": "操作成功",
                "data": {}
            }


# 读取提交日志
@luck_gitlab_log_bp.route("/gitlab/log/readAll", methods=['POST'])
def gitlab_log_read_all():
    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))}开始读取提交日志')
    config = current_app.config['CONFIG_DATA']
    parameters = json.loads(request.data)

    service = LuckGitlabLogService(config)
    result = service.read(parameters)

    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 结束读取提交日志')
    return result

# 读取用户贡献数据
@luck_gitlab_log_bp.route('/gitlab/log/readCommitData')
def gitlab_log_read_commit_data():
    day_num = request.args.get('day_num', "1")  # 第二个参数是默认值，如果q不存在则默认为空字符串
    project_code = request.args.get('project_code', "")  # 第二个参数是默认值，如果q不存在则默认为空字符串
    __gitlab_log_read_commit_data(day_num, project_code)

    return {
        "code": LuckConstant.CODE_SUCCESS,
        "msg": "同步gitlab数据成功"
    }


def __gitlab_log_read_commit_data(day_num, project_code):
    # 获取前一天的零时和23点59分59秒
    yesterday = datetime.now() - timedelta(days=int(day_num))
    start_time = yesterday.replace(hour=0, minute=0, second=0, microsecond=0).strftime('%Y-%m-%dT%H:%M:%SZ')
    # end_time = yesterday.replace(hour=23, minute=59, second=59, microsecond=0).strftime('%Y-%m-%dT%H:%M:%SZ')
    end_time = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
    config = current_app.config['CONFIG_DATA']
    config["gitlab_private_token"] = config["gitlab_private_token"]
    gitlab_log_service = LuckGitlabLogService(config)
    gitlab_log_service.process_data(start_time, end_time, project_code)